package org.lex.net.ftp.util;

import org.lex.net.ftp.IFTPClient;
import org.lex.net.ftp.LexFTPClient;
import org.lex.utils.pool.DaemonExecutor;

public abstract class FTPClientFactory {
	private static final FTPClientFactory factory = new DefaultFactory();

	public static FTPClientFactory getDefaultFactory() {
		return factory;
	}

	public abstract IFTPClient newFTPClient();

	public abstract IFTPClient newFTPClient(FTPClientConfig config);

	public void close(final IFTPClient ftp) {
		if (null == ftp || false == ftp.isServerOpen())
			return;
		DaemonExecutor.execute(new Runnable() {
			public void run() {
				while (true == ftp.isServerOpen()) {
					try {
						ftp.closeServer();
					} catch (Exception e) {
					}
					try {
						Thread.sleep(100);
					} catch (Exception e) {
					}
				}
			}
		});
	}

	private static class DefaultFactory extends FTPClientFactory {
		@Override
		public LexFTPClient newFTPClient() {
			return newFTPClient(FTPClientConfig.DEFAULT_CONFIG);
		}

		@Override
		public LexFTPClient newFTPClient(FTPClientConfig config) {
			return new LexFTPClient(config);
		}
	}
}
